using Microsoft.EntityFrameworkCore;
using RAG.Application.Interfaces;
using RAG.Application.Dtos;
using RAG.Application.Commands;
using RAG.Infrastructure.Data;
using RAG.Domain.Entities.App;

namespace RAG.Application.Services;

/// <summary>
/// 问答管理服务实现
/// </summary>
public class AppQAManagementService : IAppQAManagementService
{
    private readonly RagDbContext _db;

    public AppQAManagementService(RagDbContext db)
    {
        _db = db;
    }

    /// <summary>
    /// 获取问答列表
    /// </summary>
    public async Task<ApiResult> GetQAListAsync(Guid userId, QAListQueryDto query)
    {
        try
        {
            // 检查用户是否有查看所有问答的权限
            var canViewAll = await CheckUserCanViewAllQAAsync(userId);
            
            // 从现有的conversations表获取数据，过滤掉已删除的记录
            var queryBuilder = _db.Conversations
                .Include(c => c.User)
                .Include(c => c.Session)
                .Where(c => !c.IsDeleted) // 过滤掉已删除的记录
                .AsQueryable();

            // 根据权限过滤数据
            if (!canViewAll)
            {
                queryBuilder = queryBuilder.Where(c => c.UserId == userId);
            }

            // 关键词搜索（在问题中搜索）
            if (!string.IsNullOrEmpty(query.Keyword))
            {
                queryBuilder = queryBuilder.Where(c => c.ConversationQuestion.Contains(query.Keyword));
            }

            // 时间范围过滤
            if (query.StartDate.HasValue)
            {
                queryBuilder = queryBuilder.Where(c => c.CreatedAt >= query.StartDate.Value);
            }

            if (query.EndDate.HasValue)
            {
                queryBuilder = queryBuilder.Where(c => c.CreatedAt <= query.EndDate.Value);
            }

            var totalCount = await queryBuilder.CountAsync();

            var qaList = await queryBuilder
                .OrderByDescending(c => c.CreatedAt)
                .ThenBy(c => c.Id)
                .Skip((query.Page - 1) * query.PageSize)
                .Take(query.PageSize)
                .Select(c => new QADetailDto
                {
                    Id = c.Id,
                    SessionId = c.SessionId,
                    SessionTitle = c.Session != null ? c.Session.SessionTitle : "无会话",
                    Question = c.ConversationQuestion,
                    Answer = c.ConversationAnswer,
                    SourceChunks = c.SourceChunks,
                    Model = c.ConversationModel,
                    PromptTokens = c.PromptTokens,
                    CompletionTokens = c.CompletionTokens,
                    LatencyMs = c.LatencyMs,
                    CreatedAt = c.CreatedAt,
                    UserId = c.UserId,
                    UserName = c.User != null ? c.User.Username : "",
                    IsOwner = c.UserId == userId
                })
                .ToListAsync();

            var result = new
            {
                QAList = qaList,
                TotalCount = totalCount,
                Page = query.Page,
                PageSize = query.PageSize,
                TotalPages = (int)Math.Ceiling((double)totalCount / query.PageSize)
            };

            return ApiResult.Success("获取问答列表成功", result);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取问答列表失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取问答详情
    /// </summary>
    public async Task<ApiResult> GetQADetailAsync(Guid userId, Guid qaId)
    {
        try
        {
            var qa = await _db.Conversations
                .Include(c => c.Session)
                .FirstOrDefaultAsync(c => c.Id == qaId && c.UserId == userId && !c.IsDeleted);

            if (qa == null)
            {
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "问答记录不存在或无权限访问");
            }

            var result = new QADetailDto
            {
                Id = qa.Id,
                SessionId = qa.SessionId,
                SessionTitle = qa.Session != null ? qa.Session.SessionTitle : "",
                Question = qa.ConversationQuestion,
                Answer = qa.ConversationAnswer,
                SourceChunks = qa.SourceChunks,
                Model = qa.ConversationModel,
                PromptTokens = qa.PromptTokens,
                CompletionTokens = qa.CompletionTokens,
                LatencyMs = qa.LatencyMs,
                CreatedAt = qa.CreatedAt
            };

            return ApiResult.Success("获取问答详情成功", result);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取问答详情失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 删除问答
    /// </summary>
    public async Task<ApiResult> DeleteQAAsync(Guid userId, Guid qaId)
    {
        try
        {
            // 检查用户是否有删除所有问答的权限
            var canDeleteAll = await CheckUserCanDeleteAllQAAsync(userId);
            
            var qa = canDeleteAll 
                ? await _db.Conversations.FirstOrDefaultAsync(c => c.Id == qaId && !c.IsDeleted)
                : await _db.Conversations.FirstOrDefaultAsync(c => c.Id == qaId && c.UserId == userId && !c.IsDeleted);

            if (qa == null)
            {
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "问答记录不存在或无权限删除");
            }

            // 软删除
            qa.IsDeleted = true;
            qa.UpdatedAt = DateTime.UtcNow;
            await _db.SaveChangesAsync();
            return ApiResult.Success("删除问答成功");
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"删除问答失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 批量删除问答
    /// </summary>
    public async Task<ApiResult> BatchDeleteQAAsync(Guid userId, List<Guid> qaIds)
    {
        try
        {
            // 检查用户是否有删除所有问答的权限
            var canDeleteAll = await CheckUserCanDeleteAllQAAsync(userId);
            
            var qas = canDeleteAll
                ? await _db.Conversations.Where(c => qaIds.Contains(c.Id) && !c.IsDeleted).ToListAsync()
                : await _db.Conversations.Where(c => qaIds.Contains(c.Id) && c.UserId == userId && !c.IsDeleted).ToListAsync();

            if (!qas.Any())
            {
                return ApiResult.Failed((int)ApiStatusCode.NOT_FOUND, "未找到可删除的问答记录");
            }

            // 软删除
            foreach (var qa in qas)
            {
                qa.IsDeleted = true;
                qa.UpdatedAt = DateTime.UtcNow;
            }
            await _db.SaveChangesAsync();
            return ApiResult.Success($"成功删除 {qas.Count} 条问答记录");
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"批量删除问答失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 获取问答总数（全库）
    /// </summary>
    public async Task<ApiResult> GetQAStatisticsAsync(Guid userId)
    {
        try
        {
            // 使用Entity Framework查询，过滤掉已删除的记录
            int totalConversations = await _db.Conversations
                .Where(c => !c.IsDeleted)
                .CountAsync();

            var result = new { totalConversations };
            return ApiResult.Success("获取问答总数成功", result);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"获取问答总数失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 导出问答数据
    /// </summary>
    public async Task<ApiResult> ExportQADataAsync(Guid userId, ExportQADto exportDto)
    {
        try
        {
            // 检查用户是否有查看所有问答的权限
            var canViewAll = await CheckUserCanViewAllQAAsync(userId);
            
            var query = canViewAll
                ? _db.Conversations.Where(c => !c.IsDeleted)
                : _db.Conversations.Where(c => c.UserId == userId && !c.IsDeleted);

            // 应用过滤条件
            if (exportDto.StartDate.HasValue)
            {
                query = query.Where(c => c.CreatedAt >= exportDto.StartDate.Value);
            }

            if (exportDto.EndDate.HasValue)
            {
                query = query.Where(c => c.CreatedAt <= exportDto.EndDate.Value);
            }

            if (!string.IsNullOrEmpty(exportDto.Keyword))
            {
                query = query.Where(c => 
                    c.ConversationQuestion.Contains(exportDto.Keyword) || 
                    c.ConversationAnswer.Contains(exportDto.Keyword) ||
                    (c.Session != null && c.Session.SessionTitle.Contains(exportDto.Keyword))
                );
            }

            var qaList = await query
                .Include(c => c.Session)
                .Include(c => c.User)
                .OrderByDescending(c => c.CreatedAt)
                .Select(c => new QADetailDto
                {
                    Id = c.Id,
                    SessionId = c.SessionId,
                    SessionTitle = c.Session != null ? c.Session.SessionTitle : "无会话",
                    Question = c.ConversationQuestion,
                    Answer = c.ConversationAnswer,
                    SourceChunks = c.SourceChunks,
                    Model = c.ConversationModel,
                    PromptTokens = c.PromptTokens,
                    CompletionTokens = c.CompletionTokens,
                    LatencyMs = c.LatencyMs,
                    CreatedAt = c.CreatedAt,
                    UserId = c.UserId,
                    UserName = c.User != null ? c.User.Username : "",
                    IsOwner = c.UserId == userId
                })
                .ToListAsync();

            var result = new
            {
                Format = exportDto.Format,
                Data = qaList,
                TotalCount = qaList.Count,
                ExportTime = DateTime.UtcNow
            };

            return ApiResult.Success("导出问答数据成功", result);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"导出问答数据失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 搜索问答
    /// </summary>
    public async Task<ApiResult> SearchQAAsync(Guid userId, string keyword, int page = 1, int pageSize = 10)
    {
        try
        {
            if (string.IsNullOrEmpty(keyword))
            {
                return ApiResult.Failed((int)ApiStatusCode.BAD_REQUEST, "搜索关键词不能为空");
            }

            // 检查用户是否有查看所有问答的权限
            var canViewAll = await CheckUserCanViewAllQAAsync(userId);
            
            var query = canViewAll
                ? _db.Conversations.Where(c => !c.IsDeleted)
                : _db.Conversations.Where(c => c.UserId == userId && !c.IsDeleted);

            // 搜索关键词
            query = query.Where(c => 
                c.ConversationQuestion.Contains(keyword) || 
                c.ConversationAnswer.Contains(keyword) ||
                (c.Session != null && c.Session.SessionTitle.Contains(keyword))
            );

            var totalCount = await query.CountAsync();

            var qaList = await query
                .Include(c => c.Session)
                .Include(c => c.User)
                .OrderByDescending(c => c.CreatedAt)
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .Select(c => new QADetailDto
                {
                    Id = c.Id,
                    SessionId = c.SessionId,
                    SessionTitle = c.Session != null ? c.Session.SessionTitle : "无会话",
                    Question = c.ConversationQuestion,
                    Answer = c.ConversationAnswer,
                    SourceChunks = c.SourceChunks,
                    Model = c.ConversationModel,
                    PromptTokens = c.PromptTokens,
                    CompletionTokens = c.CompletionTokens,
                    LatencyMs = c.LatencyMs,
                    CreatedAt = c.CreatedAt,
                    UserId = c.UserId,
                    UserName = c.User != null ? c.User.Username : "",
                    IsOwner = c.UserId == userId
                })
                .ToListAsync();

            var result = new
            {
                QAList = qaList,
                TotalCount = totalCount,
                Page = page,
                PageSize = pageSize,
                TotalPages = (int)Math.Ceiling((double)totalCount / pageSize),
                Keyword = keyword
            };

            return ApiResult.Success("搜索问答成功", result);
        }
        catch (Exception ex)
        {
            return ApiResult.Failed((int)ApiStatusCode.INTERNAL_ERROR, $"搜索问答失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 检查用户是否有查看所有问答的权限
    /// </summary>
    private async Task<bool> CheckUserCanViewAllQAAsync(Guid userId)
    {
        try
        {
            // 检查用户是否有 qa.view.all 权限
            var user = await _db.Users
                .Include(u => u.Roles)
                .ThenInclude(r => r.Permissions)
                .Where(u => u.Id == userId && !u.IsDeleted)
                .FirstOrDefaultAsync();

            if (user == null)
            {
                return false;
            }

            var hasPermission = user.Roles.Any(r => r.Permissions
                .Any(p => p.PermissionCode == "qa.view.all"));

            return hasPermission;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    /// <summary>
    /// 检查用户是否有删除所有问答的权限
    /// </summary>
    private async Task<bool> CheckUserCanDeleteAllQAAsync(Guid userId)
    {
        try
        {
            // 检查用户是否有 qa.delete.all 权限
            var user = await _db.Users
                .Include(u => u.Roles)
                .ThenInclude(r => r.Permissions)
                .Where(u => u.Id == userId && !u.IsDeleted)
                .FirstOrDefaultAsync();

            if (user == null)
            {
                return false;
            }

            var hasPermission = user.Roles.Any(r => r.Permissions
                .Any(p => p.PermissionCode == "qa.delete.all"));

            return hasPermission;
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}
